import json
from django.shortcuts import render, redirect
from rest_framework.decorators import api_view, action

# Create your views here.

from app01.models import *
from django.shortcuts import HttpResponse
from django.http import *
from rest_framework import viewsets
from app01.serializers import *
from app01.models import *
from rest_framework.response import Response
from rest_framework import status


def test(request):
    if request.method == 'GET':
        test = Secretary.objects.first()
        return JsonResponse({'code': test.name})


@api_view(['POST'])
def login(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            name = data['name']
            password = data['password']
        except json.decoder.JSONDecodeError:
            return Response({'error': '请输入用户名和密码'}, status=status.HTTP_400_BAD_REQUEST)

        user = User.objects.filter(name=name).filter(password=password)
        if not user:
            return Response(data={
                'code': 0,
                'msg': '登录失败，用户名和密码不正确'
            },
                status=status.HTTP_401_UNAUTHORIZED)
        request.session['info'] = {'name': name, 'password': password}
        request.session['is_login'] = True
        request.session.set_expiry(60 * 60)
        return Response(data={
            'code': 1,
            'msg': '成功登录'
        }, status=status.HTTP_200_OK)
    return Response(data={
        'code': 0,
        'msg': '登录失败，密码不正确'
    }, status=status.HTTP_405_METHOD_NOT_ALLOWED)



@api_view(['GET'])
def logout(request):
    request.session.pop('is_login', None)
    return redirect('/login/')  # 重定向到登录页面


class EnterpriseViewSet(viewsets.ModelViewSet):
    queryset = Enterprise.objects.all()
    serializer_class = EnterpriseSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Enterprise.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class LinkmanViewSet(viewsets.ModelViewSet):
    queryset = Linkman.objects.all()
    serializer_class = LinkmanSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Linkman.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class OfficeViewSet(viewsets.ModelViewSet):
    queryset = Office.objects.all()
    serializer_class = OfficeSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Office.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ParticipateViewSet(viewsets.ModelViewSet):
    queryset = Participate.objects.all()
    serializer_class = ParticipateSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Participate.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ResearcherViewSet(viewsets.ModelViewSet):
    queryset = Researcher.objects.all()
    serializer_class = ResearcherSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Researcher.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ResearchprojectViewSet(viewsets.ModelViewSet):
    queryset = Researchproject.objects.all()
    serializer_class = ResearchprojectSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Researchproject.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ResearchroomlistViewSet(viewsets.ModelViewSet):
    queryset = Researchroomlist.objects.all()
    serializer_class = ResearchroomlistSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Researchroomlist.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class ScientificpayoffsViewSet(viewsets.ModelViewSet):
    queryset = Scientificpayoffs.objects.all()
    serializer_class = ScientificpayoffsSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Scientificpayoffs.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class SecretaryViewSet(viewsets.ModelViewSet):
    queryset = Secretary.objects.all()
    serializer_class = SecretarySerializer

    @action(detail=False, methods=['POST'])
    def search(self,request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Secretary.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)






class SubprojectViewSet(viewsets.ModelViewSet):
    queryset = Subproject.objects.all()
    serializer_class = SubprojectSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = Subproject.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @action(detail=False, methods=['POST'])
    def search(self, request):
        try:
            # 获取请求中的字段名和对应的值
            field_name = request.data.get('type')
            field_value = request.data.get('value')
            # 根据字段名和值进行过滤
            if field_name and field_value:
                # 直接匹配字段名和值
                queryset = User.objects.filter(**{field_name: field_value})
                serializer = self.get_serializer(queryset, many=True)
                return Response(serializer.data)
            else:
                return Response(
                    {'error': 'Invalid request. 请提供正确的查询数据'},
                    status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

